package com.koron.common.web.servlet;

import com.koron.common.stub.Port;
import com.koron.css2.ApplicationConfig;
import com.koron.css2.serviceManage.bean.ServicePtUserBean;
import com.koron.css2.serviceManage.bean.ServiceUserBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.serviceManage.utils.RedisUtils;
import com.koron.css2.systemManage.bean.OrgUserBean;
import com.koron.css2.systemManage.dto.UserAuthorityDto;
import com.koron.css2.systemManage.service.UserService;
import com.koron.util.Constant;
import com.koron.util.DBSourceUtils;
import com.koron.util.Tools;
import com.koron.util.UserAuthorityException;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.swan.bean.MessageBean;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Controller
public class LoginAction {
	
	@Autowired
	private UserService userService;

	private static Logger logger = LoggerFactory.getLogger(LoginAction.class);

	/**
	 * 外来人员登录营业收费（目前人员只能修改垃圾费定价 免收） 暂时屏蔽   正常添加的oa用户和外来人员还欠缺字段标识
	 */
	@RequestMapping(value = "/loginOtherCustomer.api", method = RequestMethod.POST)
	@ResponseBody
	public String loginOtherCustomer(@RequestBody ServiceUserBean userBean) throws IOException {
		MessageBean<String> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "登录成功", String.class);

		if (StringUtils.isEmpty(userBean.getLoginName())) {
			info.setDescription("非法参数");
			info.setCode(Constant.MESSAGE_INT_FAIL);
			return info.toJson();
		}

		String token = Tools.getObjectId();

		UserAuthorityDto userAuthorityDto = null;

		UserInfoBean userInfo = new UserInfoBean();
		userInfo.setCurService(Constant.APP_CUSTOMER);
		ServicePtUserBean servicePtUserBean = new ServicePtUserBean();// 本方法用于运维登陆会话信息
		servicePtUserBean.setAcount(userBean.getLoginName()); // 账号
		servicePtUserBean.setCode(userBean.getLoginName()); // code
		userInfo.setUserInfo(servicePtUserBean);
		try {
			userAuthorityDto = getUserAuthority(userInfo, ApplicationConfig.getAppCustomerAppid(), token);
			List<String> companyList = userAuthorityDto.getCompanys().stream().map(t -> t.getCompanyNo()).collect(Collectors.toList());

			String env =DBSourceUtils.getDbEnv(userAuthorityDto.getCurWaterCode());
			OrgUserBean orgUser = Tools.getOrgUserByAccount(env, userBean.getLoginName());
			if (orgUser == null) {
				logger.info("当前账户" + userBean.getLoginName() + "未在系统注册");
				info.setDescription("当前账户" + userBean.getLoginName() + "未在系统注册");
				info.setCode(Constant.MESSAGE_INT_FAIL);
				return info.toJson();
			}
			if(!orgUser.getPassword().equals(Tools.MD5(userBean.getPassword()))) {
				info.setCode(Constant.MESSAGE_INT_PWDERROR);
				info.setDescription("密码不正确");
				return info.toJson();
			}
			servicePtUserBean.setName(userAuthorityDto.getUserName());
			userInfo.setCurWaterCode(userAuthorityDto.getCurWaterCode()); // 默认选中第一个水司
			userInfo.setWaterCode(companyList);
			RedisUtils.setEx(token, ApplicationConfig.getExpireTime(), JsonUtils.objectToJson(userInfo));
		}catch(Exception ex) {
			String errmsg = "获取当前用户权限信息失败！！！";
			if(ex.getCause() instanceof UserAuthorityException) {
				errmsg = ex.getCause().getMessage();
			}
			info.setDescription(errmsg);
			info.setCode(Constant.MESSAGE_INT_FAIL);
		}
		info.setData(token);
		return info.toJson();
	}

	/**
	 * 登陆营业收费
	 * @param token
	 */
	@RequestMapping("/loginCustomer.htm")
	@ResponseBody
	public String loginCustomer(String token) throws IOException {
		Port port = new Port(ApplicationConfig.appCustomerAppid, ApplicationConfig.appCustomerSecret);
		MessageBean<?> msg = MessageBean.create(Constant.MESSAGE_INT_NOMODULE, "请先进行登录", String.class);
		// UMA 单点登录
		if (Objects.equals(Constant.UMA_SSO_PLAT, ApplicationConfig.getSsoPlatform())){
			msg = port.getStaff(Objects.toString(token, ""));
		} else if (Objects.equals(Constant.IAM_SSO_PLAT, ApplicationConfig.getSsoPlatform())) {
			// 竹云单点登录
			msg = port.getOauth2User(Objects.toString(token, ""));
		}
		if (msg.getCode() == Constant.MESSAGE_INT_NOMODULE) {
			msg.setCode(Constant.MESSAGE_INT_NOLOGIN);
			msg.setDescription("请先进行登录");
			return msg.toJson();
		}
		String loginName = "";
		String code = "";
		if(Objects.equals("1", ApplicationConfig.getAuthorityPlatform())) {
			Map<String, String> data = JsonUtils.objectToPojo(msg.getData(), Map.class);
			code = data.get("code");
			loginName = data.get("loginName");
		}else {
			loginName = (String) msg.getData();
			code = (String) msg.getData();
		}

		UserAuthorityDto userAuthorityDto = null;
		MessageBean<UserAuthorityDto> message = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "登录成功", UserAuthorityDto.class);
		UserInfoBean userInfo = new UserInfoBean();
		userInfo.setCurService(Constant.APP_CUSTOMER);
		ServicePtUserBean servicePtUserBean = new ServicePtUserBean();// 本方法用于运维登陆会话信息
		servicePtUserBean.setAcount(loginName); // 账号
		servicePtUserBean.setCode(code); // code
		userInfo.setUserInfo(servicePtUserBean);

		try {
			userAuthorityDto = getUserAuthority(userInfo, ApplicationConfig.getAppCustomerAppid(), token);
			List<String> companyList = userAuthorityDto.getCompanys().stream().map(t -> t.getCompanyNo()).collect(Collectors.toList());
			servicePtUserBean.setName(userAuthorityDto.getUserName());
			userInfo.setCurWaterCode(userAuthorityDto.getCurWaterCode()); // 默认选中第一个水司
			userInfo.setWaterCode(companyList);
			RedisUtils.setEx(token, ApplicationConfig.getExpireTime(), JsonUtils.objectToJson(userInfo));
		}catch(Exception ex) {
			String errmsg = "获取当前用户权限信息失败！！！";
			if(ex.getCause() instanceof UserAuthorityException) {
				errmsg = ex.getCause().getMessage();
			}
			ex.printStackTrace();
			logger.error(errmsg + ex);
			message.setCode(Constant.MESSAGE_INT_FAIL);
			message.setDescription(errmsg);
			return message.toJson();
		}
		message.setToken(token);
		message.setData(userAuthorityDto);
		return message.toJson();
	}

	private UserAuthorityDto getUserAuthority(UserInfoBean userInfo, String appId, String token) {
		return ADOConnection.runTask("_default", factory -> userService.getUserAuthority(factory, userInfo, appId, token), UserAuthorityDto.class);
	}
}